package com.googlecode.publicholiday.service;

import com.googlecode.publicholiday.repository.MutablePublicHolidayRepository;
import org.joda.time.LocalDate;

import static com.googlecode.publicholiday.utils.Validation.notBlank;
import static com.googlecode.publicholiday.utils.Validation.notNull;
import static org.apache.commons.lang.Validate.isTrue;

public class DefaultPublicHolidayService implements PublicHolidayService {

    private final MutablePublicHolidayRepository publicHolidayRepository;

    public DefaultPublicHolidayService(MutablePublicHolidayRepository publicHolidayRepository) {
        this.publicHolidayRepository = publicHolidayRepository;
    }

    @Override
    public boolean create(String countryCode, LocalDate holidayDate) {
        notBlank(countryCode, "Country Code cannot be null or a blank String");
        notNull(holidayDate, "Holiday Date must not ne null");
        boolean publicHolidayDoesNotExist = !isPublicHoliday(countryCode, holidayDate);
        if (publicHolidayDoesNotExist) {
            publicHolidayRepository.create(countryCode, holidayDate);
        }
        return publicHolidayDoesNotExist;
    }

    @Override
    public Iterable<LocalDate> find(String countryCode, LocalDate startDate, LocalDate endDate) {
        notBlank(countryCode, "Country Code cannot be null or a blank String");
        notNull(startDate, "Start Date cannot be null");
        notNull(endDate, "End Date cannot be null");
        isTrue(endDate.compareTo(startDate) > 0, "End Date must be greater than the Start Date");
        return publicHolidayRepository.find(countryCode, startDate, endDate);
    }

    @Override
    public boolean delete(String countryCode, LocalDate holidayDate) {
        notBlank(countryCode, "Country Code cannot be null or a blank String");
        notNull(holidayDate, "Holiday Date must not ne null");
        return publicHolidayRepository.delete(countryCode, holidayDate);
    }

    @Override
    public boolean isPublicHoliday(String countryCode, LocalDate dateInQuestion) {
        notBlank(countryCode, "Country Code cannot be null or a blank String");
        notNull(dateInQuestion, "Holiday Date must not ne null");
        return publicHolidayRepository.find(countryCode, dateInQuestion) != null;
    }
}
